<!--
 * @Description: 产品栏目管理
 * @Author: yyh
 * @Date: 2021-06-23 16:27:30
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-27 21:05:07
-->
<template>
  <div class="column-list">
    <!-- 添加按钮 -->
    <div class="Add">
      <div><el-button class="btn" type="primary" @click="toAdd">添加</el-button></div>
    </div>
    <!-- 表单 -->
    <div class="form">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column
          width="50"
          type="index"
          label="序号"
        />
        <el-table-column
          prop="id"
          label="栏目编号"
        />
        <el-table-column
          prop="name"
          label="名称"
        />
        <el-table-column
          align="center"
          width="50"
          label="图标"
        >
          <template slot-scope="scope">
            <!-- scope是当前temlate -->
            <!-- <img src="scope.row.photo" alt=""> -->
            <!-- {{scope.row.icon}} -->

            <el-image
              style="width: 30px; height:30px"
              :src="scope.row.icon"
              :preview-src-list="[scope.row.icon]"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="num"
          label="排序号"
        />
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-button type="text" size="small" @click="toEdit(scope.row)">编辑</el-button>
            <el-button style="color:red" type="text" size="small" @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-div">
      <!-- 分页 -->
      <el-pagination
        :current-page="params.page"
        :page-sizes="[5,10,15,20,30]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 模态框 对话框 -->
    <div>
      <el-dialog :title="title" :visible.sync="visible" @close="toClose">
        <!-- {{form}} -->
        <el-form ref="ruleForm" :model="form" :rules="rules">
          <el-form-item prop="name" label="名称" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="num" label="排序号" :label-width="formLabelWidth">
            <el-input v-model="form.num" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="icon" label="图标" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible=false">取 消</el-button>
          <el-button type="primary" @click="toSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import { pageQuery, saveOrUpdate, deleteById } from '@/api/infoCategory'
import { showFileURL, uploadFileURL } from '@/utils/config'

export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      // 表格展示的数据
      tableData: [],
      // 分页参数
      params: {
        page: 1,
        pageSize: 10
      },
      // 总条数
      total: 0,
      // 加载
      loading: false,
      // 模态框的显示与隐藏
      visible: false,
      // 表单
      formLabelWidth: '80px',
      // 表单数据
      form: {},
      title: '',
      // 图片url
      imageUrl: '',
      // 校验规则
      rules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        icon: [{
          required: true,
          message: '请上传图标',
          trigger: 'change'
        }]
      }
    }
  },
  computed: {},
  // 深度监听分页参数
  watch: {
    params: {
      handler() {
        this.queryData()
      },
      deep: true
    }
  },
  created() {
    //   发请求
    //   this.queryCategoryData();
    this.queryData()
  },
  mounted() {},
  methods: {
    // 分页模糊获取栏目数据
    async queryData() {
      this.loading = true
      // 处理数据
      const temp = {
        ...this.params
      }
      // 遍历对象
      for (const key in temp) {
        // key是一个变量，代表的属性名
        // key 'page'  temp.key temp[key]
        console.log(key, temp[key])
        if (!temp[key]) {
          delete temp[key]
        }
      }
      const res = await pageQuery(temp)
      // 加载完毕
      this.loading = false
      this.tableData = res.data.list
      this.total = res.data.total
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // this.params.pageSize=val;
      this.params = {
        page: 1,
        pageSize: val
      }
      // this.queryData()
    },
    // 当前页码发生变化时的事件处理程序
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.params.page = val
      // this.queryData()
    },
    // 添加按钮事件处理程序
    toAdd() {
      //   this.queryCategoryData();
      this.form = {}
      this.imageUrl = ''
      this.title = '添加栏目信息'
      this.visible = true
    },
    // 编辑按钮事件处理程序
    toEdit(row) {
      // this.queryCategoryData();
      // 设置表单数据
      this.form = { ...row }
      this.imageUrl = this.form.icon
      this.title = '编辑栏目信息'
      this.visible = true
    },
    // 删除按钮事件处理程序
    toDelete(id) {
      this.$confirm('此操作将永久删除该栏目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async(valid) => {
        const res = await deleteById({ id })
        if (valid) {
          // 提示用户删除成功
          this.$notify({
            title: '删除成功',
            message: res.message,
            type: 'success'
          })
          this.queryData()
          // this.toClose();
          this.visible = false
        } else {
          // 提示用户删除失败
          this.$notify({
            title: '删除失败',
            message: res.message,
            type: 'error'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.icon = showFileURL + res.data.id
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 模态框确定按钮事件处理程序
    toSave() {
      // 获取dom的值，对值进行校验 form.name
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          // 校验通过，做自己的业务
          //   console.log("校验通过");
          const res = await saveOrUpdate(this.form)
          console.log(res)
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.queryData()
          // this.toClose();
          this.visible = false
        } else {
          // 校验不通过
          return false
        }
      })
    },
    // 关闭模态框
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields()

      // 超时调用,在多少毫秒后执行函数
      // setTimeout(()=>{this.visible=false;},10)
    }
  }
}
</script>
<style scoped>
.Add{
    display: flex;
}
.Add .btn{
    margin-right: 10px;
}
.form{
    padding-top: 20px;
}
</style>
